from django.shortcuts import render
from django.views import View
from django.http import HttpResponse,Http404,JsonResponse
import json
from django.forms.models import model_to_dict
from datetime import datetime, date
from django_filters.rest_framework import DjangoFilterBackend


from rest_framework.views import APIView  # 继承django的view
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from rest_framework import mixins
from rest_framework import generics
from rest_framework import viewsets
from rest_framework.filters import SearchFilter, OrderingFilter

from .models import Good, GoodMultimedia
from .serializers import *
from .filters import *
from apps.pagination import *


# Create your views here.

# class GoodsListView(View):
#     # TemplateView直接生成上下文、GoodlistView可分页，都是为了方便python模板的使用。
#     # 前后端分离开发，与python的模板语言关系不大，所以用到View可以分发dispatch get、post就足够了
#
#     # def get(self,request):
#     #
#     #     # (一)
#     #     # goods = Good.objects.all()[:10]  # queryset
#     #     # records = []
#     #     # for good in goods:
#     #         # record = {}
#     #         # record['title'] = good.title  # 不能用good['title']
#     #         # record['code'] = good.code
#     #         # record['size'] = good.size
#     #         # record['price_purchase'] = good.price_purchase
#     #         # record['price_sell'] = good.price_sell
#     #         # record = model_to_dict(good)
#     #         # records.append(record)
#     #     # return HttpResponse(json.dumps(records), classmethod=CusEncode, content_type='application/json')
#     #
#     #     # （二）
#     #     # object : queryset 迭代器 不执行sql语句 减小压力
#     #     # object : python数据对象 dict str int datetime
#     #     # python object => json object
#     #     # class CusEncode(json.JSONEncoder):
#     #     #     # json.dumps转化的结果是python的字符串，json.loads将字符串转化为python的数据结构
#     #     #     def default(self, obj):
#     #     #         # isinstance(obj, (date, datetime))
#     #     #         # datetime继承date，所以判断isinstance时，判断是否是datetime的子类在先
#     #     #         if isinstance(obj, datetime):
#     #     #             return obj.strftime('%Y-%m-%d %H:%M:%S')
#     #     #         # datetime得写在date前面
#     #     #         elif isinstance(obj, date):
#     #     #             return obj.strftime('%Y-%m-%d')
#     #     #         else:
#     #     #             return json.JSONEncoder.default(self, obj)
#     #     #
#     #     # goods = Good.objects.all()[:10]  # queryset
#     #     # records = []
#     #     # # 从数据库中取出数据
#     #     # for good in goods:
#     #     #     record = model_to_dict(good)
#     #     #     records.append(record)
#     #     # return HttpResponse(json.dumps(records, cls=CusEncode), content_type='application/json')
#     #     # (三)
#     #     goods = Good.objects.all()[:10]  # queryset
#     #     from django.core.serializers import serialize
#     #     records = serialize('json',goods)  # 结果是字符串
#     #     # return HttpResponse(records, content_type='application/json')
#     #     from django.http import JsonResponse
#     #     return JsonResponse(json.loads(records), safe=False)


# mixins准备了不同的类，不同的类有不同的方法，继承这些mixin，就可以自由组合并重写方法，mixins方便组合和重写增删改查model的方法
# 而继承自django view的任何view都好，最基本的就是为了dispatch request分发请求，是get、post还是其他
# view APIView GenericAPIView(封装了更多的属性和方法如份分页、查询、序列化，方便调用重写)

# class GoodsListView(generics.ListAPIView):
#     '''
#     description
#     GoodsListView
#     '''
#     queryset = Good.objects.all()  # queryset
#     serializer_class = GoodSerializer
#     pagination_class = StandardResultsSetPagination

'''
GenericView有属性queryset也有方法get_queryset
属性queryset是固定的取出全部 或 写死参数过滤
方法queryset，def queryset(self):，能通过url获取参数self.request.data/self.request.query_params，灵活过滤
'''
class GoodListViewSet(viewsets.ModelViewSet):

    """
    GoodListViewSet 多行注释.JPEG.
    　　　　　　　　　　　　　　　　　　　　　　　　　　　　　　　　　　　　　　　　　　　　　　　　　　　　　　　　　　　　
    This viewset automatically provides `list`, `create`, `retrieve`,
    `update` and `destroy` actions.

    Additionally we also provide an extra `highlight` action.

    """

    queryset = Good.objects.all()  # queryset
    serializer_class = GoodWithMediaGroupSerializer
    pagination_class = StandardResultsSetPagination
    filter_backends = (DjangoFilterBackend, SearchFilter, OrderingFilter)
    # fields和class二选一
    # filter_fields = '__all__'
    filter_class = GoodFilter
    search_fields = ('title',)  # 正则 ^ = @ $
    # 配置了filter_backends但不配置fields则默认为'__all__'




# class GoodsMultimediaListView(View):
#     def get(self, request):
#         GoodMultimedias = GoodMultimedia.objects.all()[:10]  # queryset
#         from django.core.serializers import serialize
#         records = serialize('json',GoodMultimedias)  # 结果是字符串
#         return JsonResponse(json.loads(records), safe=False)
#         # return HttpResponse(records, content_type='application/json')


# class GoodsMultimediaListView(APIView):
#     '''
#     description
#     GoodMultimediaListView
#     '''
#     def get(self, request, format=None):
#         GoodMultimedias = GoodMultimedia.objects.all()[:10]  # queryset
#         serializer = GoodMultimediaSerializer(GoodMultimedias, many=True)  # many=True queryset为迭代器
#         return Response(serializer.data)
#         # drf封装的response : /media/good/multimedia/201902253296401.jpg
#         # django httpresponse jsonresponse : good/multimedia/201902253296400.jpg


class GoodMultimediaListViewSet(viewsets.ModelViewSet):
    queryset = GoodMultimedia.objects.all()
    serializer_class = GoodMultimediaSerializer
    pagination_class = StandardResultsSetPagination


class GoodMultimediaWithDetailedGoodListViewSet(viewsets.ModelViewSet):
    queryset = GoodMultimedia.objects.all()
    serializer_class = MediaWithDetailedGoodSerializer
    pagination_class = StandardResultsSetPagination


# view 分发http方法get/post/delete/...
# mixin 对model操作list/retrieve/create/destroy/...
# viewset 重载as_view，绑定http方法和model操作
